package com.zx.platform.verifycode;

import org.apache.log4j.Logger;

import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * VerifyCodeBuilder
 *
 * @author Qizhan Lu
 * @version 1.0
 */
public class VerifyCodeBuilder
{
    private static final Logger LOGGER = Logger.getLogger(VerifyCodeBuilder.class );

    public static IVerifyCode buildVerifyCode()
    {

       int range = 26;
        int    base = 10;
        char[] code = new char[4];
        Random ran = new Random( System.currentTimeMillis() );
        for ( int i = 0 ; i < 4; i++ )
        {
            int value = ran.nextInt( range ) + base;
            if ( value < 10 )
            {
                // ���ֶ�
                code[i] = ( char ) ( value + 48 );
            }
            else
            {
                // ��д��ĸ��
                code[i] = ( char ) ( value + 55 );
            }
        }
        // ��������ʱ��
        Calendar timeoutTime = Calendar.getInstance();
        timeoutTime.add( Calendar.SECOND, 60 );

        return new VerifyCodeImpl( new String( code ), timeoutTime.getTime() );
    }

    /**
     * ��֤���ڲ�ʵ����
     */
    private static class VerifyCodeImpl implements IVerifyCode
    {
        private String code;

        private Date timeoutTime;

        private VerifyCodeImpl( String code, Date timeoutTime )
        {
            this.code = code;
            this.timeoutTime = timeoutTime;
        }

        public String getCode()
        {
            return code;
        }

        public boolean isMatch( String toMatch )
        {
            return !isTimeout() && code.equalsIgnoreCase( toMatch );
        }

        public boolean isTimeout()
        {
            return timeoutTime.compareTo( new Date() ) < 0;
        }
    }
}
